/*
 * Copyright (c) 2012 Johan Fylling
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy 
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights 
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 * copies of the Software, and to permit persons to whom the Software is 
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in 
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 * THE SOFTWARE.
 */

part of ClientLib;


class WebGameEngine extends GameEngine {
  num              _lastUpdate  = null;
  num              _fpsAverage  = null;
  Element          _infoElement = null;
  CollisionManager cm;
  
  WebGameEngine (PhysicsEngine pe, 
                 GraphicsEngine ge, 
                 WorldState ws, 
                 CollisionManager cm) : super(pe, ge, ws, cm),
                                        this.cm = cm;
  
  void start () {
    _infoElement = query("#info");
    frame(0);
  }
  
  frame (num time) {
    window.requestAnimationFrame(frame);
    num deltaTime = 0;
    if (_lastUpdate != null) {
      deltaTime = time - _lastUpdate;
      if (deltaTime < 20) {
        // Only update every other frame.
        return;
      }
      calcPerformance(time);
    }
    _lastUpdate = time;
    step(32);
  }
  
  void calcPerformance (num time) {
    num delta = time - _lastUpdate;
    num fps = delta != 0 ? 1000 / delta : 0;
    if (_fpsAverage == null) {
      _fpsAverage = fps;
    }
    
    _fpsAverage = fps * 0.1 + _fpsAverage * 0.9;
    
    if (_infoElement != null) {
      _infoElement.text = "delta:${delta.floor()}, "
                          "actors:$actorsUpdateDelta, "
                          "effects:$effectsUpdateDelta, "
                          "physics:$physicsUpdateDelta, "
                          "collision:$collisionDetectionDelta, "
                          "graphics:$graphicsUpdateDelta, "
                          "fps:${_fpsAverage.round()}, "
                          "collisions:${cm.collisionCount}/${cm.collisionPairCount}";
    }
  }
}
